//
//  ZDDOAuthViewController.swift
//  小蜗牛_新浪微博
//
//  Created by 周冬冬 on 16/6/25.
//  Copyright © 2016年 我的mac. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZDDOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    private func setupNavc(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelClick")
         navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillClick")
        
        navigationItem.title = "OAuth登录"
    
    
    
    
    }
    // MARK: - 监听事件
    @objc private func cancelClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillClick(){
//       
        let jsString = "document.getElementById('userId').value='18317712729',document.getElementById('passwd').value='Zdd5255949'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
        
    }
    //  MARK: - 设置视图
    private func setupUI(){
    
    
        view.backgroundColor = UIColor.whiteColor()
        setupNavc()
    
    
    }
    
    private lazy var webView:UIWebView = {
    let view = UIWebView()
        
        view.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
        
        let request = NSURLRequest(URL: url)
        
        view.loadRequest(request)
   
    return view
    
    }()
    
}

extension ZDDOAuthViewController : UIWebViewDelegate{

    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }

//完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
     //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
//    webView将要加载ResQuest
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        
        if let u = urlString where u.hasPrefix(REDIRECT_URI){
        //请求诗句
        let query = request.URL?.query
            //判断可选值
            if let q = query{
                //字符串的截取
            let code = q.substringFromIndex("code=".endIndex)
            loadUserAccount(code)
                //拿到数据后无需加在
            return false
            }
        
        }
        
        return true
    }
}
extension ZDDOAuthViewController {

    func loadUserAccount(code:String) {
    
        ZDDNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
//            
            guard let res = response as? [String:AnyObject] else {
            print("返回的数据不是一个字典")
            
                return
            }
            //字典转模型
            let userAccount = ZDDUserAccount(dict: res)
            self.loadUserInfor(userAccount)
            }) { (error) -> () in
                
                print(error)
                
        }
    
    
    }

    func loadUserInfor(userAccount:ZDDUserAccount){
    
        ZDDNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            //判断是否有值
            guard let res = response as? [String :AnyObject]
                else{
            
            return
            
            }
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            
            //通过归档保存
        ZDDUserAccountTools.sharedTools.saveUserAccount(userAccount)
            print(userAccount)
            //移除该界面
          self.dismissViewControllerAnimated(false, completion: { () -> Void in
            //关闭指示器
            SVProgressHUD.dismiss()
            
            NSNotificationCenter.defaultCenter().postNotificationName(SwiftRootVCNoti, object: nil)
          })
            

            }) { (error) -> () in
               
                print("失败\(error)")
        }
    
    }

}















